use rand::Rng;
use std::cmp::Ordering;
use std::io;

fn main() {
    println!("猜数字!");

    let secret_number = rand::thread_rng().gen_range(1..=100);
    println!("神秘数字是: {secret_number}");

    loop {
        println!("请输入你的猜测.");

        let mut guess = String::new();

        io::stdin()
            .read_line(&mut guess)
            .expect("Failed to read line");

        // let guess: u32 = match guess.trim().parse() {
        //     Ok(num) => num,
        //     Err(_) => {
        //         println!("请输入一个数字!");
        //         continue;
        //     },
        // };
        if let Ok(guess) = guess.trim().parse::<u32>() {
            println!("你猜的数字是: {guess}");

            match guess.cmp(&secret_number) {
                Ordering::Less => println!("太小!"),
                Ordering::Greater => println!("太大!"),
                Ordering::Equal => {
                    println!("恭喜你猜对了!");
                    break;
                }
            }
        } else {
            println!("请输入一个数字!");
            continue;
        }
    }

    println!("神秘数字是: {secret_number}");

    println!("游戏结束!");

    let mut play_again = String::new();

    println!("是否重新开始游戏? (y/n)");

    io::stdin()
        .read_line(&mut play_again)
        .expect("读取输入失败");

    if play_again.trim() == "y" {
        main();
    } else {
        println!("谢谢游玩!");
    }
}
